package simple;

import java.util.*;

/**
 * @author liujianxin
 * @date 2019-08-03 16:34
 */
public class TwoSum {

    public static void main(String[] args) {
        int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, List<Integer>> intMap = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            List<Integer> list;
            if ((list = intMap.get(nums[i])) == null) {
                list = new ArrayList<>();
                list.add(i);
                intMap.put(nums[i], list);
            } else {
                list.add(i);
            }
        }

        for (int i = 0; i < nums.length; i++) {
            int need = target - nums[i];
            List<Integer> other = intMap.get(need);
            if (other != null) {
                for (Integer integer : other) {
                    if (integer != i) {
                        return new int[]{i, integer};
                    }
                }
            }

        }
        return null;
    }
}
